import { onMounted, onUnmounted, ref } from 'vue';
import { isFunction } from '/@/utils/is.ts';

/**
 * @desc 定时刷新
 * @param time
 * @param callback
 */

export function useRefresh(time = 3000, callback?: Function) {
    const refreshState = ref(false);
    const timer = ref(null);

    function setRefreshState() {
        startRefresh();
    }

    function stopRefresh() {
        clearInterval(timer.value);
        timer.value = null;
    }

    function startRefresh() {
        timer.value = setInterval(() => {
            refreshState.value = !refreshState.value;
            if (callback && isFunction(callback)) {
                callback();
            }
        }, time);
    }

    onMounted(() => {
        if (timer.value != null) {
            timer.value = null;
        }
        setRefreshState();
    });

    onUnmounted(() => {
        stopRefresh();
    });
    return {
        refreshState,
        stopRefresh,
        startRefresh,
    };
}